package org.linlinjava.litemall.db.service;
import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallCashMapper;
import org.linlinjava.litemall.db.domain.LitemallCash;
import org.linlinjava.litemall.db.domain.LitemallCashExample;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.domain.LitemallUserExample;
import org.linlinjava.litemall.db.util.CashConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallCashService {

    @Autowired
    private LitemallCashMapper cashMapper;

    public void deleteById(Integer id) {
        cashMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallCash cash) {
        cash.setAddTime(LocalDateTime.now());
        cash.setUpdateTime(LocalDateTime.now());
        cashMapper.insertSelective(cash);
    }

    public List<LitemallCash> querySelective(Integer userId, String username, Integer page, Integer limit, String sort, String order) {
        LitemallCashExample example = new LitemallCashExample();
        LitemallCashExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);

        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }
        PageHelper.startPage(page, limit);
        return cashMapper.selectByExample(example);
    }

    public int updateById(LitemallCash issue) {
        issue.setUpdateTime(LocalDateTime.now());
        return cashMapper.updateByPrimaryKeySelective(issue);
    }

    public LitemallCash findById(Integer id) {
        return cashMapper.selectByPrimaryKey(id);
    }

    public LitemallCash findByUidUnCheck(Integer userId) {
        LitemallCashExample example = new LitemallCashExample();
        example.or().andUserIdEqualTo(userId).andStatusEqualTo(CashConstant.STATUS_WAIT).andDeletedEqualTo(false);
        return cashMapper.selectOneByExample(example);
    }
}
